import g
import time
from chkapidata import chk_api_data


async def do_api(uid, gateway_url, request):
    """api逻辑处理"""

    api_name = request["p"]
    module = g.m[api_name]
    # 没有这个模块
    if not module:
        return {"s": -1, "errmsg": f'api module no exists: [{api_name}]'}

    # 参数校验
    api_data = request["d"]
    _chkRes = chk_api_data(api_data, api_name)
    if _chkRes["s"] != 1:
        return _chkRes

    data = _chkRes["data"]

    if api_name == "login.login":
        data.ip = request["ip"]

    # 开始执行接口逻辑
    s_time = time.time()
    _res = await module.proc(uid, gateway_url, data)
    do_time = round((time.time() - s_time) * 1000, 2)

    _res.update({
        "api": api_name,
        "do_time": f"{do_time}ms ->【{g.C.DATE(many=True)}】"
    })

    return _res
